const { dateFormat } = require('@/utils/common.util')
const imModel = require('@/models/im.model')
const userModel = require('@/models/user.model')
const userFocusUserModel = require('@/models/user_focus_user.model')

const receiveMessage = async function (messageData = {}) {
  const { id, fromId, toId, content, image, imageWidth, imageHeight, sendTime, sendTimeStamp, quoteContent } = messageData
  const targetUserValidResult = await imRestrictValid(fromId, toId)
  if (!targetUserValidResult.sendSuccessFlag) {
    return {
      ...targetUserValidResult,
      id
    }
  }
  try {
    const receiveTime = dateFormat(new Date())
    await imModel.create({
      id,
      fromId,
      toId,
      content,
      image,
      imageWidth,
      imageHeight,
      sendTime,
      sendTimeStamp,
      receiveTime,
      quoteContent
    })
    const message = await imModel.findOneById(id)
    return {
      ...message,
      sendSuccessFlag: true
    }
  } catch (error) {
    return {
      id,
      sendSuccessFlag: false,
      failMessage: '服务器开小差了，请重试。'
    }
  }
}

/**
 * 服务端socket发送消息
 * @param {*} message
 * @param {*} client
 */
const sendMessage = function (message, client) {
  if (client) {
    const postMessage = typeof message === 'object' ? JSON.stringify(message) : String(message)
    client.send(postMessage)
  }
}

/**
 * 用户身份认证失败断开scoket连接
 * @param {*} client
 * @returns
 */
const authenticationFail = function (client) {
  client.send(JSON.stringify({
    authenticate: false,
    code: '9999',
    message: '身份认证失败，连接断开'
  }))
  sendMessage('authentication-failed', client)
  client.close()
}

/**
 * 消息接收人数据校验以及消息接收人接收消息限制校验
 * @param {} userId
 * @returns
 */
const imRestrictValid = async (fromId, toId) => {
  try {
    const userInfo = await userModel.findOne({ id: toId })
    if (!userInfo) {
      return {
        sendSuccessFlag: false,
        failMessage: '消息接收人不存在。'
      }
    }
    const imRestrict = userInfo.imRestrict
    // 关闭私信
    if (imRestrict === '3') {
      return {
        sendSuccessFlag: false,
        failMessage: '对方已经关闭私信功能，无法收到你发送的消息。'
      }
    }
    // 允许互相关注的人私信
    if (imRestrict === '2') {
      const foucus = await userFocusUserModel.findOne(fromId, toId)
      const focused = await userFocusUserModel.findOne(toId, fromId)
      console.log(foucus, focused)
      if (!(foucus && focused)) {
        return {
          sendSuccessFlag: false,
          failMessage: '对方已经开启非互相关注私信限制，只接受来自好友的私信。'
        }
      }
    }
    if (imRestrict === '1') {
      const foucus = await userFocusUserModel.findOne(toId, fromId)
      if (!foucus) {
        return {
          sendSuccessFlag: false,
          failMessage: '对方已经开启非他/她关注私信限制，只接受他关注的人的私信。'
        }
      }
    }
    return {
      sendSuccessFlag: true
    }
  } catch (error) {
    console.log(error)
    return {
      sendSuccessFlag: false,
      failMessage: '服务器开小差了，请重试。'
    }
  }
}

module.exports = {
  receiveMessage,
  sendMessage,
  authenticationFail
}
